<template>
  <el-dialog v-model="isdialogTableVisible" title="处方详情" width="900px">
    <div class="drug-box-all" ref="printComponentRef" id="printableArea" v-print-nb
      :class="medicines.length > 1 ? 'page-break-after-always':'' ">
      <div class="drug-box">
        <div class="drug-title font-85"> 肖瘤处方笺 </div>
        <div class="drug-user-info font-85">
          <div class="drug-user-list drug-user-list-1">
            <div class="drug-user-left">姓名：</div>
            <div class="drug-user-right"> {{prescriptionAll.doctor_name}} </div>
          </div>
          <div class="drug-user-list drug-user-list-2">
            <div class="gender">
              <div class="drug-user-left">性别：</div>
              <div class="drug-user-right"> {{prescriptionAll.patient_sex==1?'男':'女'}} </div>
            </div>
            <div class="age">
              <div class="drug-user-left">年龄：</div>
              <div class="drug-user-right"> {{prescriptionAll.patient_age}}岁 </div>
            </div>
          </div><!---->
          <div class="drug-user-list drug-user-list-3">
            <div class="drug-user-left">联系电话：</div>
            <div class="drug-user-right">{{prescriptionAll.patient_mobile}}</div>
          </div>
          <div class="drug-user-list drug-user-list-4">
            <div class="drug-user-left">加工方式：</div>
            <div class="drug-user-right" style="width: calc(100% - 60px);"><img
                src="https://images.dayiketang.com/zijian.png" alt="" class="jg-img"></div>
          </div>
          <div class="drug-user-list drug-user-list-1">
            <div class="drug-user-left">科室：</div>
            <div class="drug-user-right"> {{prescriptionAll.doctor_department}} </div>
          </div>
          <div class="drug-user-list drug-user-list-2">
            <div class="drug-user-left">处方编号：</div>
            <div class="drug-user-right"> {{prescriptionAll.order_sn}} </div>
          </div>
          <div class="drug-user-list drug-user-list-3">
            <div class="drug-user-left">开方日期：</div>
            <div class="drug-user-right">{{prescriptionAll.confirm_at}}</div>
          </div>
        </div>
        <div class="drug-content">
          <div class="drug-content-left">
            <div class="drug-content-left-top font-85"> 临床诊断： </div>
            <div class="drug-content-left-bottom font-85" ><span>
              </span><span  v-for="(item,index) in prescriptionAll.diagnosis" :key="index">{{item.name}}; </span></div>
          </div>
          <div class="drug-content-right">
            <div class="drug-content-right-top font-85"> R: <span class="drug-status font-65" v-if="prescriptionAll.process_nam">（{{prescriptionAll.process_name}}）</span></div>
            <div class="drug-content-right-bottom clearfix">
              <div class="drug-detail" v-if="prescriptionAll.prescription_items.drugList.length>0" v-for="(item,index) in prescriptionAll.prescription_items.drugList"><span class="left">{{item.drug_name}} {{getMath(item.drug_num)}}{{item.unit_name}} <span v-if="prescriptionAll.process_id == 2">{{item.standard_type == 1?'企标':(item.standard_type == 2 ? '省标' : '国标')}}</span></span>
                <div class="drug-mark font-65"><span v-if="item.decoction_id !=0" style="position: absolute;top:-11px">{{item.decoction_name}}</span>
                <!-- v-if="item.is_sign == 1" -->
                  <div class="drug-mark-2" ><img  src="https://images.dayiketang.com/FglXBKALvg3iAiY-tTyhx-yexMXx" alt=""
                      class="sign-image"></div>
                </div>
              </div>
              <div class="drug-content-footer font-65">
                <div class="drug-content-mark">
                  <div class="drug-content-mark-1"><span> 共{{prescriptionAll.drug_weight}}g </span><span>，每剂约3g</span><span
                      class="pl-5 pr-5">用法用量：</span><span>{{prescriptionAll.usage_name}}</span>{{templateText}}</div>
                </div>
                <div class="drug-content-doctor"> 医生签名（签章）： <img
                    :src="prescriptionAll.physician_sign" alt="" class="drug-doctor-img">
                </div>
                <div class="drug-content-mark-2 yizhu"><span class="font-85">医嘱：</span><span v-for="(item,indx) in prescriptionAll.doctor_advice_arr" :key="index">{{ item.text}}</span> </div>
                <!----><!---->
              </div>
            </div><!---->
          </div>
        </div>
        <div class="drug-footer font-65">
          <div class="drug-footer-list">
            <div class="drug-footer-left">审核：</div>
            <div class="drug-footer-right"><img
                :src="getItemById(prescriptionAll.staff_info,1)"
                alt="" class="sign_img"></div>
          </div>
          <div class="drug-footer-list">
            <div class="drug-footer-left">调配：</div>
            <div class="drug-footer-right"><img
                :src="getItemById(prescriptionAll.staff_info,2)"
                alt="" class="sign_img"></div>
          </div>
          <div class="drug-footer-list">
            <div class="drug-footer-left">核对：</div>
            <div class="drug-footer-right"><img
                :src="getItemById(prescriptionAll.staff_info,3)"
                alt="" class="sign_img"></div>
          </div>
          <div class="drug-footer-list">
            <div class="drug-footer-left">发药：</div>
            <div class="drug-footer-right"><img
                :src="getItemById(prescriptionAll.staff_info,4)"
                alt="" class="sign_img"></div>
          </div>
          <div class="drug-remark-box">
            注：1、请遵医嘱用药；2、请将药品放于阴凉干燥处保存；3、本处方3日内有效；4、因各药房药名录入规则不同，同一种药在纸质处方与电子处方中的药名显示可能不同； </div>
        </div>

      </div>
      <div class="drug-page">第1页，共1页</div>
    </div>
    <div slot="title" class="bottonBtn">
      <el-button type="primary">去发货</el-button>
      <el-button type="success" v-print="printOption">打印</el-button>
      <el-button type="success" :loading="savePdf" @click="clickPdf(1)">保存为PDF</el-button>
      <el-button type="success" :loading="savePdfG" @click="clickPdf(2)">保存为PDF(盖章)</el-button>
      <el-button @click="isdialogTableVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
  import print from 'vue3-print-nb'
  import html2pdf from 'html2pdf.js';
  import html2canvas from 'html2canvas';
  import jsPDF from 'jspdf';
  import {nextTick,onMounted,reactive,ref,toRaw} from "vue";
  import {pharmacistExamineShow} from '/src/api/orderManage/recipeOrder'
  import {useLimit} from '/src/api/drug/drugProcess.js'
  const props = defineProps({
    prescriptionOrderId: { type: String }
  })
  const savePdf = ref(false)
  const savePdfG = ref(false)
  const isdialogTableVisible = ref(false)
  const patientName = ref('张三');
  const gender = ref('男');
  const age = ref(30);
  const phoneNumber = ref('1234567890');
  const diagnosis = ref('感冒');
  const doctorName = ref('李医生');
  const department = ref('中医科');
  const doctorPhoneNumber = ref('0987654321');
  const currentDate = ref('');
  const medicines = ref([{
      name: '人参',
      dosage: '10g',
      usage: '煎服'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    },
    {
      name: '枸杞',
      dosage: '15g',
      usage: '泡水饮用'
    }
  ]);
  const vPrint = print;
  const printOption = ref({
    id: 'printableArea', // 打印元素的id 不需要携带#号
    popTitle: '处方订单详情 - 骁柔大后台', // 页眉标题 默认浏览器标题 空字符串时显示undefined 使用html语言
    preview: false, // 开启打印预 
  })
  const getStyle = () => {
    return medicines.length > 1 ? {
      'page-break-after': 'always'
    } : {};
  }
  const prescriptionAll=ref({})
//处方详情接口
  const getPharmacistExamineShow = async (prescriptionId) => {
    try {
      const result = await pharmacistExamineShow({
        id:props.prescriptionOrderId,
        prescription_id: prescriptionId
      })
      if (result.code == 200) {
        console.log('处方详情接口',result.data)
        prescriptionAll.value=result.data
        getUseLimit(result.data.use_limit_id)
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }
  
  //用法用量
  // const useLimit=ref([])
  const getUseLimit = async (id) => {
    try {
      const result = await useLimit()
      if (result.code == 200) {
       // useLimit.value= result.data
       checkList(result.data,id)
      }
    } catch (error) {
      console.error('获取列表时出错：', error)
    }
  }
  
  const templateText=ref('')
  const checkList=(list,id)=>{
    const item = list.find(item => item.id === id);
    // return item ? item.sign_url : null;
    templateText.value=replaceX(item.value,prescriptionAll.value.use_limit)
  }
  const replaceX = (str, array) => {
    let result = str; // 将原始字符串赋值给结果
    array.forEach((element) => {
      // 用数组中的元素替换字符串中的第一个 "X"
      result = result.replace("X", element);
    });
    return result;
  };
  
  


  const openNotesDia = (prescriptionId) => {
    getPharmacistExamineShow(prescriptionId)
    isdialogTableVisible.value = true
  }
  
  const getMath=(num)=>{
    return  Math.floor(num * 10) / 10;
  }
  const getItemById = (list,id) => {
        const item = list.find(item => item.type === id);
        return item ? item.sign_url : null;
  };

  const printComponentRef = ref(null);
  const clickPdf2 = (type) => {
    const element = document.getElementById('printableArea');
    const opt = {
      margin: 1, // pdf外边距
      filename: 'pdf生成' + '.pdf', // 导出的pdf名称
      image: { // 图片的类型和质量，详情： https://github.com/eKoopmans/html2pdf.js#image-type-and-quality
        type: 'jpeg',
        quality: 0.98 // 取0-1，默认0.95，仅适用  jpeg/webp
      },
      html2canvas: {
        scale: 1,
        dpi: 92,
      },
      jsPDF: { // 详情：http://www.rotisedapsales.com/snr/cloud2/website/jsPDF-master/docs/jsPDF.html
        unit: 'pt', // pt、mm、cm、in
        format: 'a4',
        orientation: 'landscape' // 纵向p，横向l
      }
    };


    // Call the library function to generate PDF
    html2pdf().from(element).set(opt).save();

  }

  const contentToPrint = ref(null);

  const clickPdf = () => {
    const content = document.getElementById('printableArea');

    html2canvas(content, {
      scale: 2,
      x: -10, // 调整截图起始横坐标
      y: -10, // 调整截图起始纵坐标
      width: content.offsetWidth + 20, // 调整截图宽度
      height: content.offsetHeight + 20 // 调整截图高度
    }).then(canvas => {
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF({
        orientation: 'landscape',
        unit: 'px',
        format: [canvas.width, canvas.height]
      });

      const width = pdf.internal.pageSize.getWidth();
      const height = pdf.internal.pageSize.getHeight();

      pdf.addImage(imgData, 'PNG', 0, 0, width, height);
      pdf.save('generated_pdf.pdf');
    });
  }

  defineExpose({
    openNotesDia
  })
</script>

<style lang="scss" scoped>
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid pink;
    font-size: 16px;
    color: #17233d;
  }

  .font-85 {
    color: rgba(0, 0, 0, 0.85);
  }

  .drug-box-all {
    width: 100%;
    /* 设置内容宽度为100% */
    height: auto;
    /* 高度自适应内容 */
    font-family: "Arial", sans-serif;
    /* 使用支持中文字符的字体 */
    padding-bottom: 20px;
  }

  .drug-box {
    margin: 0 auto;
    width: 804px;
    min-height: 547px;
    border: 1px solid #000;
    box-sizing: border-box;
    padding: 10px 8px 0;
  }

  .drug-box .drug-title {
    width: 100%;
    height: 32.4px;
    line-height: 32.4px;
    font-size: 21.6px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 5.4px;
  }

  .drug-box .drug-user-info {
    height: 43.2px;
    width: 100%;
    padding: 0 0 0 5.4px;
    margin-bottom: 5.4px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
  }

  .drug-box .drug-user-info .drug-user-list-1 {
    width: 202.5px;
  }

  .drug-box .drug-user-info .drug-user-list {
    height: 21.6px;
  }

  .drug-box .drug-user-info .drug-user-list .drug-user-left,
  .drug-box .drug-user-info .drug-user-list .drug-user-right {
    float: left;
    width: auto;
    height: 21.6px;
    line-height: 21.6px;
    font-size: 12px;
    position: relative;
  }

  .drug-box .drug-user-info .drug-user-list .drug-user-left,
  .drug-box .drug-user-info .drug-user-list .drug-user-right {
    float: left;
    width: auto;
    height: 21.6px;
    line-height: 21.6px;
    font-size: 12px;
    position: relative;
  }

  .drug-box .drug-user-info .drug-user-list-2 {
    width: 216px;
  }

  .drug-box .drug-user-info .drug-user-list {
    height: 21.6px;
  }

  .drug-box .drug-user-info .drug-user-list-3 {
    width: 216px;
  }

  .drug-box .drug-user-info .drug-user-list {
    height: 21.6px;
  }

  .drug-box .drug-user-info .drug-user-list-4 {
    width: 135px;
  }

  .drug-box .drug-user-info .drug-user-list {
    height: 21.6px;
  }

  .drug-box .drug-user-info .drug-user-list .drug-user-left .jg-img,
  .drug-box .drug-user-info .drug-user-list .drug-user-right .jg-img {
    width: 76px;
    height: 59px;
    position: absolute;
    top: -34px;
    left: 0;
  }

  .drug-box .drug-content {
    width: 781.65px;
    height: 395.8px;
  }

  .drug-box .drug-content .drug-content-left {
    padding: 8.1px 5.4px;
    box-sizing: border-box;
  }


  .drug-box .drug-content .drug-content-left .drug-content-left-top,
  .drug-box .drug-content .drug-content-right .drug-content-left-top {
    width: 100%;
    height: 24.3px;
    line-height: 24.3px;
    font-size: 13.5px;
    text-align: left;
  }

  .drug-box .drug-content .drug-content-left .drug-content-left-bottom,
  .drug-box .drug-content .drug-content-right .drug-content-left-bottom {
    width: 100%;
    line-height: 14.3px;
    font-size: 12.15px;
    height: calc(100% - 40.5px);
    overflow: hidden;
    text-align: justify;
  }

  .drug-box .drug-content .drug-content-right {
    width: calc(100% - 118.8px);
    border-left: none;
    padding: 4.05px 5.4px;
    box-sizing: border-box;
    position: relative;
  }

  .drug-box .drug-content .drug-content-left {
    float: left;
    width: 118.8px;
    height: 100%;
    border: 1px solid #bfbfbf;
    border-right: none;
  }

  .drug-box .drug-content .drug-content-right {
    float: right;
    width: calc(100% - 118.8px);
    height: 100%;
    border: 1px solid #bfbfbf;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-top {
    width: 100%;
    height: 32.4px;
    line-height: 32.4px;
    font-size: 18.9px;
    font-weight: bold;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-top .drug-status {
    display: inline-block;
    font-size: 12.15px;
    line-height: 24.3px;
    font-weight: normal;
  }

  .font-65 {
    color: rgba(0, 0, 0, 0.65);
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom {
    width: 100%;
    height: calc(100% - 32.4px);
    box-sizing: border-box;
    position: relative;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail {
    float: left;
    width: 25%;
    height: 23px;
    margin: 3.1px 0 0;
    font-size: 12.15px;
    color: rgba(0, 0, 0, 0.65);
  }

  .left {
    float: left;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail .drug-mark {
    max-width: 58.25px;
    min-width: 47.25px;
    width: auto;
    transform: scale(0.6);
    transform-origin: top center;
    margin: 0;
    display: flex;
    justify-items: flex-start;
    align-items: center;
    flex-wrap: wrap;
    align-content: center;
    position: relative;
    justify-content: center;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail .drug-mark .drug-mark-1,
  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail .drug-mark .drug-mark-2 {
    float: left;
    width: 100%;
    height: 20.76px;
    line-height: 20.76px;
    font-size: 16px;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail .drug-mark .drug-mark-1 img,
  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-detail .drug-mark .drug-mark-2 img {
    width: 100%;
    vertical-align: top;
    -o-object-fit: contain;
    object-fit: contain;
    position: relative;
    top: 0;
    left: 0;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer {
    width: 100%;
    clear: both;
    position: absolute;
    bottom: 0px;
    left: 0;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-mark {
    width: calc(100% - 210px);
    height: 21.6px;
    float: left;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-mark .drug-content-mark-1 {
    width: 100%;
    height: 21.6px;
    line-height: 21.6px;
    font-size: 12.15px;
  }

  .pl-5 {
    padding-left: 5px;
  }

  .pr-5 {
    padding-right: 5px;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-doctor {
    float: left;
    width: 210px;
    height: 21.6px;
    line-height: 21.6px;
    font-size: 12.15px;
    text-align: right;
    overflow: hidden;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-doctor .drug-doctor-img {
    max-height: 100%;
    vertical-align: middle;
    -o-object-fit: contain;
    object-fit: contain;
    transform: scale(1.03);
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-mark .drug-content-mark-1 {
    width: 100%;
    height: 21.6px;
    line-height: 21.6px;
    font-size: 12.15px;
  }

  .drug-box .drug-content .drug-content-right .drug-content-right-bottom .drug-content-footer .drug-content-mark-2 {
    width: 100%;
    line-height: 16.6px;
    font-size: 12.15px;
  }

  .yizhu {
    word-break: break-all;
  }

  .drug-box .drug-footer {
    width: 100%;
    margin-top: 2.7px;
    padding: 0 5.4px;
    box-sizing: border-box;
  }

  .drug-box .drug-footer .drug-footer-list {
    width: 25%;
    height: 16px;
    float: left;
  }

  .drug-box .drug-footer .drug-footer-list .drug-footer-left,
  .drug-box .drug-footer .drug-footer-list .drug-footer-right {
    float: left;
    height: 16px;
    line-height: 16px;
    font-size: 12px;
  }

  .drug-box .drug-footer .drug-footer-list .drug-footer-left,
  .drug-box .drug-footer .drug-footer-list .drug-footer-right {
    float: left;
    height: 16px;
    line-height: 16px;
    font-size: 12px;
  }

  .sign_img {
    max-height: 16px;
    width: auto;
  }

  .drug-box .drug-footer .drug-remark-box {
    width: 100%;
    line-height: 16px;
    font-size: 12px;
    clear: both;
  }

  .drug-page {
    width: 100%;
    height: 12px;
    line-height: 12px;
    font-size: 12px;
    text-align: center;
    color: #000;
    position: relative;
    top: 8px;
  }

  .page-break-after-always {
    page-break-after: always !important;
  }

  .bottonBtn {
    width: 100%;
    text-align: center;
    margin-top: 20px;
  }

  #your-element-id {
    width: 297mm;
    /* Width of A4 in landscape */
    height: 210mm;
    /* Height of A4 in landscape */
    font-family: "Arial", sans-serif;
    /* Specify a font that supports Chinese characters */
    /* Add any other styles you need */
  }

  @media print {
    .print-content {
      width: 21cm;
      /* Adjust to fit within A4 width */
      margin: 0 auto;
      /* Center the content */
      /* Additional styles as needed */
    }
  }

  @media print {
    @page {
      size: auto;
    }

    body,
    html {
      height: auto !important;
    }
  }
</style>